<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="仓库编码">
        <el-input v-model="queryParams.warehouse_code" placeholder="请输入仓库编码" clearable></el-input>
      </el-form-item>
      <el-form-item label="仓库名称">
        <el-input v-model="queryParams.warehouse_name" placeholder="请输入仓库名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" plain @click="handleAdd">
        <i class="el-icon-plus"></i> 新增
      </el-button>
      <el-button type="success" plain :disabled="selectedRows.length !== 1" @click="handleEdit(selectedRows[0])">
        <i class="el-icon-edit"></i> 修改
      </el-button>
      <el-button type="danger" plain :disabled="!selectedRows.length" @click="handleDelete()">
        <i class="el-icon-delete"></i> 批量删除
      </el-button>
      <div class="top-right-btn">
        <el-button icon="el-icon-search" circle />
        <el-button icon="el-icon-refresh" circle @click="getList" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%;font-size: 12px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="warehouse_code" label="仓库编码" align="center">
        <template slot-scope="{row}">
          <el-button type="text" @click="handleViewWarehouse(row)">{{ row.warehouse_code }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="warehouse_name" label="仓库名称" align="center"></el-table-column>
      <el-table-column prop="location" label="位置" align="center"></el-table-column>
      <el-table-column prop="area" label="面积" align="center">
        <template slot-scope="{row}">{{ row.area }} ㎡</template>
      </el-table-column>
      <el-table-column label="已用容量" align="center">
        <template slot-scope="{row}">
          <span :style="getUsageStyle(row)">{{ getUsagePercent(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="charge_name" label="负责人" align="center"></el-table-column>
      <el-table-column prop="frozen_flag" label="是否冻结" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.frozen_flag"
            active-value="Y"
            inactive-value="N"
            @change="handleFrozenChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="center"></el-table-column>
      <el-table-column prop="warehouse_id" label="操作"  align="center" width="200">
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleStorageArea(row.warehouse_id)">
            <i class="el-icon-s-shop"></i> 库区
          </el-button>
          <el-button type="text" @click="handleEdit(row)">
            <i class="el-icon-edit"></i> 修改
          </el-button>
          <el-button type="text" @click="handleDelete(row)">
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="仓库编码" prop="warehouse_code">
          <div style="display: flex; align-items: center;">
            <el-input v-model="form.warehouse_code" placeholder="请输入仓库编码" :disabled="form.autoCode || form.warehouse_id" style="flex:1;" />
            <el-switch v-model="form.autoCode" style="margin-left:10px;" @change="handleAutoCodeChange" :disabled="!!form.warehouse_id" />
            <span style="margin-left:5px; white-space:nowrap;">自动生成</span>
          </div>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouse_name">
          <el-input v-model="form.warehouse_name" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item label="面积">
          <el-input-number v-model="form.area" :min="1" :step="1" style="width: 180px;" />
        </el-form-item>
        <el-form-item label="负责人" prop="charge_name">
          <el-input v-model="form.charge_name" placeholder="点击右侧按钮选择负责人" readonly>
            <template slot="append">
              <el-button icon="el-icon-search" @click="handleUserSearchOpen"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否冻结" prop="frozen_flag">
          <el-switch v-model="form.frozen_flag" active-value="Y" inactive-value="N" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户选择弹窗 -->
    <el-dialog title="人员选择" :visible.sync="userDialogVisible" width="900px">
      <div style="margin-bottom: 16px; display: flex; align-items: center;">
        <el-input v-model="queryParamsUser.userName" placeholder="请输入用户名" style="width: 200px; margin-right: 10px;" />
        <el-input v-model="queryParamsUser.phonenumber" placeholder="请输入手机号" style="width: 200px; margin-right: 10px;" />
        <el-button type="primary" icon="el-icon-search" @click="handleUserSearch">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="handleUserReset" style="margin-left: 10px;">重置</el-button>
      </div>
      <el-table :data="userList" highlight-current-row :row-key="row => row.userId" style="width: 100%;">
        <el-table-column label=" " width="50" align="center">
          <template slot-scope="scope">
            <el-radio v-model="userId" :label="scope.row.userId" @change="handleUserSelect(scope.row)">
              <span style="display: none;"></span>
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" align="center" />
        <el-table-column prop="nickName" label="用户昵称" align="center" />
        <el-table-column prop="dept.deptName" label="部门" align="center" />
        <el-table-column prop="phonenumber" label="手机号" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" />
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="totalUser>0"
          :total="totalUser"
          :page.sync="queryParamsUser.pageNum"
          :limit.sync="queryParamsUser.pageSize"
          @pagination="fetchUserList"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUserDialogOk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增只读弹窗 -->
    <el-dialog title="查看仓库信息" :visible.sync="viewDialogVisible" width="800px" append-to-body>
      <el-form label-width="100px" :model="viewWarehouse">
        <el-row>
          <el-col :span="12">
        <el-form-item label="仓库编码">
              <el-input v-model="viewWarehouse.warehouse_code" placeholder="暂无数据" readonly />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="仓库名称">
              <el-input v-model="viewWarehouse.warehouse_name" placeholder="暂无数据" readonly />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="位置">
              <el-input v-model="viewWarehouse.location" placeholder="暂无数据" readonly />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="面积">
              <el-input :value="viewWarehouse.area ? `${viewWarehouse.area} ㎡` : ''" placeholder="暂无数据" readonly />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="负责人">
              <el-input v-model="viewWarehouse.charge_name" placeholder="暂无数据" readonly />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="是否冻结">
              <el-input :value="viewWarehouse.frozen_flag === 'Y' ? '是' : '否'" placeholder="暂无数据" readonly />
        </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="viewWarehouse.remark" placeholder="暂无数据" readonly type="textarea" />
        </el-form-item>
      </el-form>

      <el-divider content-position="center">库位信息</el-divider>

      <el-table v-loading="locationLoading" :data="locationData" height="250">
        <el-table-column label="库位编码" prop="location_code" align="center" />
        <el-table-column label="库位名称" prop="location_name" align="center" />
        <el-table-column label="面积(㎡)" prop="area" align="center" />
        <el-table-column label="已用容量(%)" prop="used_capacity" align="center" />
        <el-table-column label="是否冻结" prop="frozen_flag" align="center">
           <template slot-scope="scope">{{ scope.row.frozen_flag === 'Y' ? '是' : '否' }}</template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="locationTotal>0"
        :total="locationTotal"
        :page.sync="locationQueryParams.pageNum"
        :limit.sync="locationQueryParams.pageSize"
        @pagination="getLocationsList"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { listWs, saveWs, updateFrozen, listSls, deleteWarehouseBatch } from "@/views/ck/js/setup"
import { listUser } from '@/api/system/user'
import Pagination from "@/components/Pagination"
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";

export default {
  components: {
    Pagination
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      loading: false,
      selectedRows: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouse_code: undefined,
        warehouse_name: undefined
      },
      // 用户查询参数
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 总条数
      total: 0,
      totalUser: 0,
      open: false,
      title: '',
      form: {
        warehouse_id: '',
        warehouse_code: '',
        warehouse_name: '',
        location: '',
        area: 1,
        charge_id: '',
        charge_name: '',
        frozen_flag: 'N',
        remark: '',
        create_by: '',
        update_by: '',
        locations: [], // 确保 locations 是一个空数组
        autoCode: false
      },
      rules: {
        warehouse_code: [
          { required: true, message: '仓库编码不能为空', trigger: 'blur' }
        ],
        warehouse_name: [
          { required: true, message: '仓库名称不能为空', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '位置不能为空', trigger: 'blur' }
        ],
        charge_name: [
          { required: true, message: '请选择负责人', trigger: ['blur', 'change'] }
        ]
      },
      frozenState:{
        id: '',
        type: 1,
        state: ''
      },
      userDialogVisible: false,
      userList: [],
      userSelected: null,
      userId: null,
      viewDialogVisible: false,
      viewWarehouse: {},
      locationData: [],
      locationLoading: false,
      locationTotal: 0,
      locationQueryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouse_id: null
      }
    };
  },
  mounted() {
    this.getList();
  },
  methods: {

    // 获取数据列表
    getList() {
      this.loading = true;
      listWs(this.queryParams).then(resp => {
        console.log("测试获取数据:", resp);
        this.tableData = resp.rows;
        this.total = resp.total
        this.loading = false;
      }).catch(error => {
        console.error("获取数据失败:", error);
        this.loading = false;
      });
    },
    // 搜索按钮
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    handleReset() {
      this.queryParams.warehouse_code = undefined,
      this.queryParams.warehouse_name = undefined
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 表格多选
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    // 状态切换
    handleFrozenChange(row) {
      const newStatus = row.frozen_flag;
      const oldStatus = newStatus === 'Y' ? 'N' : 'Y';
      const actionText = newStatus === 'Y' ? '冻结' : '解冻';

      this.$confirm(`确认要${actionText}仓库"${row.warehouse_name}"吗？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: `正在${actionText}，请稍候...`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        // 确认操作，保持新状态
        this.frozenState.id = row.warehouse_id
        this.frozenState.state = row.frozen_flag
        updateFrozen(this.frozenState).then(resp => {
          loading.close();
          if(resp.flag){
            this.$message.success(`${actionText}成功`);
          }else{
            this.$message.error(`${actionText}失败`);
            row.frozen_flag = oldStatus; // 失败时恢复原状态
          }
        }).catch(() => {
          loading.close();
          row.frozen_flag = oldStatus; // 异常时恢复原状态
          this.$message.error(`${actionText}失败`);
        });

      }).catch(() => {
        // 取消操作，恢复原状态
        row.frozen_flag = oldStatus;
        this.$message.info('已取消操作');
      });
    },
    // 操作按钮
    handleAdd() {
      this.reset();
      this.form.autoCode = true;
      this.handleAutoCodeChange(true);
      this.open = true;
      this.title = '新增仓库';
    },
    handleEdit(row) {
      // 回显选中仓库信息到表单
      this.form = Object.assign({}, row)
      this.open = true;
      this.title = '修改仓库';
    },
    handleDelete(row) {
      const warehouseIds = row ? [row.warehouse_id] : this.selectedRows.map(item => item.warehouse_id);
      const warehouseNames = row ? row.warehouse_name : this.selectedRows.map(item => item.warehouse_name).join(', ');
      this.$confirm('删除仓库将同时删除其下的所有库区和库位，是否确认删除仓库名称为"' + warehouseNames + '"的数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
        }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在删除，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        deleteWarehouseBatch(warehouseIds).then(response => {
          loading.close();
          if (response.code === 200) {
            this.getList();
            this.$message.success("删除成功");
          } else {
            this.$message.error(response.msg);
          }
        }).catch(() => {
          loading.close();
          this.$message.error("删除操作失败");
          });
      }).catch(() => {});
    },
    //查看库区
    handleStorageArea(warehouseId) {
      this.$router.push({
        path: '/ck/setup/Area',
        query: { warehouseId: warehouseId }
      });
    },
    handlePrint(row) {
      console.log('标签打印', row);
    },
    // 不需要单独的分页方法，因为使用了@pagination="getList"

    // 显示已用容量百分比
    getUsagePercent(row) {
      // 直接使用后台返回的used_capacity字段
      return row.used_capacity + '%';
    },

    // 根据使用率设置样式
    getUsageStyle(row) {
      // 将字符串转为数值进行比较
      const usageRate = parseInt(row.used_capacity || 0);
      return {
        color: usageRate >= 80 ? '#ff4949' : '#67c23a',
        fontWeight: 'bold'
      };
    },
    reset() {
      this.form = {
        warehouse_code: '',
        warehouse_name: '',
        location: '',
        area: 1,
        charge_id: '',
        charge_name: '',
        frozen_flag: 'N',
        remark: '',
        autoCode: false
      };
    },
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在提交数据，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          // 修改逻辑
          if (this.form.warehouse_id) {
            this.form.update_by = this.$store.getters.name; // 只更新修改人
      saveWs(this.form).then(resp => {
              loading.close();
              if (resp.flag) {
                this.open = false;
                this.getList();
                this.$message.success("修改成功");
              } else {
                this.$message.error(resp.msg || "修改失败");
              }
            }).catch(() => {
              loading.close();
              this.$message.error("修改操作失败");
            });
          }
          // 新增逻辑
          else {
            if (this.form.autoCode) {
              try {
                const response = await getAutoNumbersConsume(13);
                if (response.code === 200) {
                  this.form.warehouse_code = response.msg;
                } else {
                  this.$message.error('获取仓库编号失败: ' + response.msg);
                  loading.close();
                  return;
                }
              } catch (error) {
                this.$message.error('获取仓库编号失败');
                loading.close();
                return;
              }
            }
            this.form.create_by = this.$store.getters.name;
            this.form.update_by = this.$store.getters.name;

            saveWs(this.form).then(saveResp => {
              loading.close();
              if (saveResp.flag) {
          this.open = false;
                this.getList();
                this.$message.success("新增成功");
              } else {
                this.$message.error(saveResp.msg || "新增失败");
        }
            }).catch(() => {
              loading.close();
              this.$message.error("新增操作失败");
            });
          }
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    handleAutoCodeChange(val) {
      if (val) {
        getAutoNumbers(13).then(resp => {
          this.form.warehouse_code = resp.msg;
        });
      } else {
        this.form.warehouse_code = '';
      }
    },
    handleUserSearch() {
      this.queryParamsUser.pageNum = 1;
      this.fetchUserList();
    },
    handleUserReset() {
      this.queryParamsUser.userName = '';
      this.queryParamsUser.phonenumber = '';
      this.queryParamsUser.pageNum = 1;
      this.fetchUserList();
    },
    fetchUserList() {
      this.loading = false
      listUser(this.queryParamsUser).then(resp => {
        this.userList = resp.rows
        this.totalUser = resp.total
        this.loading = false
        // 默认选中第一行
        if (this.userList.length > 0) {
          this.userSelected = this.userList[0]
          this.userId = this.userList[0].id
        } else {
          this.userSelected = null
          this.userId = null
        }
      })
    },
    handleUserPageChange(page) {
      this.userPagination.current = page;
      this.fetchUserList();
    },
    handleUserSelect(row) {
      this.userSelected = row
      this.userId = row.userId
      this.form.charge_id = row.userId
    },
    handleUserDialogOk() {
      if (this.userSelected) {
        this.form.charge_name = this.userSelected.nickName || this.userSelected.userName;
      }
      this.userDialogVisible = false;
    },
    // 打开用户选择弹窗时加载数据
    handleUserSearchOpen() {
      this.userDialogVisible = true;
      this.fetchUserList();
    },
    handleViewWarehouse(row) {
      this.viewWarehouse = Object.assign({}, row);
      this.locationQueryParams.warehouse_id = row.warehouse_id;
      this.getLocationsList();
      this.viewDialogVisible = true;
    },
    getLocationsList() {
      this.locationLoading = true;
      listSls(this.locationQueryParams).then(response => {
        this.locationData = response.rows;
        this.locationTotal = response.total;
        this.locationLoading = false;
      });
    }
  }
};
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.operation-buttons {
  margin-bottom: 20px;
}
.pagination-right {
  text-align: right; /* 右对齐 */
  margin-top: 30px;
}
</style>
